package entity.units;

import entity.Attackable;
import entity.Entity;
import entity.building.Building;
import levels.PathFinder;
import loading.ImageLoader;
import math.Vector2D;

public abstract class AttackUnit extends GroundUnit implements Attacker
{
	protected static final int ATTACKING = 3;
	
	private Attackable target;
	
	private double attackRadius;
	private int damage;
	private double coolDown;
	private double timeUntilCoolDown;

	public AttackUnit( Vector2D pos, ImageLoader img, PathFinder pf, double timeToTrain, int totalHealth, double attackRadius, int damage, double coolDown )
	{
		super( pos, img, pf, timeToTrain, totalHealth );
		
		target = null;
		
		this.attackRadius = attackRadius;
		this.damage = damage;
		
		this.coolDown = timeUntilCoolDown = coolDown;
	}
	
	public void attack( Attackable target )
	{
		this.target = target;
		
		if( target instanceof Building )
		{
			super.goTo( ((Building)target).getClosestAttackLocation( this.getPosition() ) );
		}
		else
			super.goTo( ((Entity)target).getPosition() );
	}
	
	public void goTo( Vector2D end )
	{
		super.goTo( end );
		
		target = null;
	}
	
	public void update( double duration )
	{
		super.update( duration );
		
		if( getState() == STANDING && target != null )
		{
			if( target instanceof Building )
			{
				super.goTo( ((Building)target).getClosestAttackLocation( this.getPosition() ) );
			}
			else
				super.goTo( ((Entity)target).getPosition() );
		}
		
		if( getState() == MOVING && target != null )
		{
			if( ((Entity)target).getPosition().distance( this.getPosition() ) <= attackRadius )
			{
				setState( ATTACKING );

				this.setSpeed( 0 );
			}
			
			if( target.isDead() )
			{
				target = null;
				
				super.stop();
			}
		}
		
		if( getState() == ATTACKING )
		{
			if( ((Entity)target).getPosition().distance( this.getPosition() ) > attackRadius )
			{
				if( target instanceof Building )
				{
					super.goTo( ((Building)target).getClosestAttackLocation( this.getPosition() ) );
				}
				else
					super.goTo( ((Entity)target).getPosition() );
			}
			else if( timeUntilCoolDown >= coolDown )
			{
				target.damage( damage );
				
				timeUntilCoolDown = 0;
			}
			
			if( target.isDead() )
			{
				target = null;
				
				super.stop();
			}
		}
		
		if( timeUntilCoolDown < coolDown )
			timeUntilCoolDown += duration;
	}
}
